//
//  ViewController.m
//  Command
//
//  Created by Hechun on 2020/11/7.
//

#import "ViewController.h"

// util
#import "ReadColorCommand.h"

#import "CommandManager.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) CommandManager *manager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
       static dispatch_once_t onceToken;
       dispatch_once(&onceToken, ^{
//           [self viewDidLoad];
       });
    
    [self asyncConcurrent];
    
    // Do any additional setup after loading the view.
//    [self.view addSubview:self.tableView];
//    [self.tableView reloadData];
}

/**
 * 异步执行 + 并发队列
 * 特点：可以开启多个线程，任务交替（同时）执行。
 */
- (void)asyncConcurrent {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"asyncConcurrent---begin");
    
    // 并发队列的创建方法
//    dispatch_queue_t queue = dispatch_queue_create("com.hechun.testQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        // 任务1
//        sleep(2);
        [CommandManager semaphoreManager];
        NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
    });
    dispatch_async(queue, ^{
        // 任务2
//        sleep(2);
        [CommandManager semaphoreManager];
        NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
    });
    dispatch_async(queue, ^{
        // 任务3
//        sleep(2);
        [CommandManager semaphoreManager];
        NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
    NSLog(@"asyncConcurrent---end");
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (self.dataArray && [self.dataArray isKindOfClass:[NSArray class]] && self.dataArray.count > indexPath.row) {
        NSDictionary *dic = self.dataArray[indexPath.row];
        if ([dic isKindOfClass:[NSDictionary class]]) {
            NSString *newsId = dic[@"id"];
            ReadColorCommand *cmd = [[ReadColorCommand alloc] init];
            [cmd colorWithNewsId:newsId finish:^(UIColor * _Nonnull color) {
                cell.textLabel.textColor = color;
            }];
            
            NSString *title = dic[@"title"];
            cell.textLabel.text = title;
        }
    }
    
    
    return cell;;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.dataArray[indexPath.row];
    if ([dic isKindOfClass:[NSDictionary class]]) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *newsId = dic[@"id"];
        ReadColorCommand *cmd = [[ReadColorCommand alloc] init];
        [cmd saveNewsId:newsId finish:^(UIColor * _Nonnull color) {
            cell.textLabel.textColor = color;
        }];
    }
}

#pragma mark - Lazy

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
}

- (NSArray *)dataArray {
    if (!_dataArray) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
        NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];
        NSError *error;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        if ([jsonArray isKindOfClass:[NSArray class]]) {
            _dataArray = jsonArray;
        } else {
            _dataArray = [NSArray array];
        }
    }
    
    return _dataArray;
}

@end
